<template>
  <div class="loginbox">
    <!-- 遮罩层 -->
    <div class="mask" @click="changeIsShowLoginModal(false)"></div>
    <!-- 登录盒子 -->
    <div class="login">
      <div class="close" @click="changeIsShowLoginModal(false)"></div>
      <!-- 登录导航切换 -->
      <section>
        <a
          href="javascript:;"
          :class="{ active: isShowLogin }"
          @click="isShowLogin = true"
          >手机号码登录</a
        >
        |
        <a
          href="javascript:;"
          :class="{ active: !isShowLogin }"
          @click="showQrFn"
          >微信扫码登录</a
        >
      </section>
      <div class="content">
        <div class="phonelogin" v-show="isShowLogin">
          <div class="row">
            <input
              type="text"
              placeholder="请输入手机号"
              v-model="phoneNumber"
            />
          </div>
          <div class="row">
            <slide-verify
              :l="42"
              :r="20"
              :w="350"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
              :imgs="imgarr"
            ></slide-verify>
          </div>
          <div class="row">
            <input type="text" placeholder="请输入验证码" v-model="dxcode" />
            <button class="btn btncode" @click="getCode" v-show="!isShowCount">
              获取验证码
            </button>
            <button class="btn btncode" v-show="isShowCount">
              {{ count }}
            </button>
          </div>
          <div class="row">
            <button class="btn btnlogin" @click="submitFn">登录</button>
          </div>
        </div>
        <div class="qrlogin" v-show="!isShowLogin" id="weixin">
          微信扫码登录盒子
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapMutations, mapActions } from "vuex";
import { validatePhoneNumber } from "@/utils";
import { SendSMSAPI, PhoneReginAPI, BindingAPI } from "@/request/api";
export default {
  methods: {
    ...mapMutations({
      changeIsShowLoginModal: "showModal/changeIsShowLoginModal",
      changeIsLogin: "loginStatus/changeIsLogin",
    }),
    ...mapActions({
      asyncShowToast: "showToast/asyncShowToast",
    }),
    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },
    // 封装的校验手机号和滑块验证码
    toVerify() {
      // 1.判断手机号
      if (!validatePhoneNumber(this.phoneNumber)) {
        // 显示提示组件，并自动隐藏
        this.asyncShowToast({
          isShow: true,
          msg: "请输入正确的手机号",
          type: "error",
        });
        return;
      }
      // 2.判断滑块验证码
      if (this.msg == "再试一次" || this.msg == "向右滑动") {
        // 显示提示组件，并自动隐藏
        this.asyncShowToast({
          isShow: true,
          msg: "请完成滑块验证码",
          type: "error",
        });
        return;
      }
      // 以上都不执行，函数默认返回undefined，需要return true
      return true;
    },
    // 校验滑块验证码
    async getCode() {
      // 1.判断手机号
      /* 
        正则表达式：
         ^ 以^后面的开头     $ 以$后面的结尾   
         \d就是[0-9]  {8}就是校验8次
         .test(验证的字符串)
         手机号验证封装到utils文件夹
      */
      // let reg =
      //   /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      // if (!reg.test(this.phoneNumber)) {
      //   alert("请输入正确的手机号");
      //   return;
      // }
      // if (!validatePhoneNumber(this.phoneNumber)) {
      //   alert("请输入正确的手机号");
      //   return;
      // }

      // 2.判断滑块验证码
      // if (this.msg == "再试一次" || this.msg == "向右滑动") {
      //   alert("请完成滑块验证码");
      //   return;
      // }

      if (!this.toVerify()) return;

      // 3.获取验证码(发送请求给后台)
      let res = await SendSMSAPI({
        phone: this.phoneNumber,
      });
      // 获取失败
      if (!res) return;
      // 短信验证倒计时
      this.isShowCount = true;
      let timer = setInterval(() => {
        this.count--;
        if (this.count == 0) {
          clearInterval(timer);
          this.count = 6;
          this.isShowCount = false;
        }
      }, 1000);
    },

    // 4.发送登录请求
    async submitFn() {
      if (!this.toVerify()) return;
      // 发送请求时区分，如果有uuid表示微信登录关联手机号的登录请求，没有的话就是普通的手机号登录
      let uuid = localStorage.getItem("uuid");
      let res = null;
      if (uuid) {
        console.log("发起关联请求");
        res = await BindingAPI({
          phone: this.phoneNumber,
          verifyCode: this.dxcode,
          uuid,
        });
      } else {
        res = await PhoneReginAPI({
          phone: this.phoneNumber,
          verifyCode: this.dxcode,
        });
      }

      if (!res) return;
      // 1.弹框
      this.asyncShowToast({
        isShow: true,
        msg: "登录成功",
        type: "success",
      });
      // 2.隐藏登录框
      this.changeIsShowLoginModal(false);
      // 3.储存token
      localStorage.setItem("x-auth-token", res["x-auth-token"]);
      // 4.登录后隐藏登录按钮显示购物车
      this.changeIsLogin(true);
      // 5.清除本地uuid
      if (uuid) {
        localStorage.removeItem("uuid");
      }
    },
    showQrFn() {
      this.isShowLogin = false;
      // 微信二维码步骤3：实例化
      // 申请微信登录二维码
      let _this = this;
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://127.0.0.1:8080" + _this.$route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLA0KLmltcG93ZXJCb3ggLmluZm8gew0KICAgIGRpc3BsYXk6IG5vbmU7DQp9DQoNCi5pbXBvd2VyQm94IHFyY29kZSB7DQogICAgbWFyZ2luLXRvcDogMjBweDsNCn0=",
      });
      /*
      修改样式：utils->创建wxLoginStyle文件夹 ->创建wxlogin.css
      */
    },
  },
  data() {
    return {
      isShowLogin: true,
      msg: "向右滑动",
      imgarr: [
        require("../assets/img/integral-01.9386d4bf.png"),
        require("../assets/img/integral-02.150d92a1.png"),
        require("../assets/img/integral-03.9870f3f1.png"),
        require("../assets/img/integral-04.afadcbdf.png"),
      ],
      phoneNumber: "",
      count: 6,
      isShowCount: false,
      // 短信验证码
      dxcode: "",
    };
  },
};
</script>

<style lang="less" scoped>
.loginbox {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  .mask {
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
  }
  .login {
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    margin: auto;
    width: 555px;
    height: 423px;
    background: url("../assets/img/login-box-bg.png");
    .close {
      width: 22px;
      height: 22px;
      position: absolute;
      right: 60px;
      top: 15px;
      background: url("../assets/img/close.png");
    }
    section {
      line-height: 40px;
      padding-top: 40px;
      text-align: center;
      a {
        text-decoration: none;
        color: #000;
        &.active {
          color: red;
        }
      }
    }
    .content {
      width: 350px;
      margin: 0 auto;
      text-align: center;
      .phonelogin {
        .row {
          display: flex;
          margin-top: 20px;
          input {
            flex: 1;
            height: 45px;
            text-indent: 1em;
            outline: none;
          }
          .btn {
            background-color: rgb(10, 50, 142);
            color: #fff;
            border: none;
          }
          .btncode {
            margin-left: 10px;
            width: 80px;
          }
          .btnlogin {
            width: 100%;
            height: 45px;
          }
        }
      }
    }
  }
}

/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>
